package com.property.demo.config;

import com.property.demo.model.*;
import com.property.demo.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.stream.Collectors;

@Configuration
public class DataLoader {

    private static final Logger logger = LoggerFactory.getLogger(DataLoader.class);
    private final PasswordEncoder passwordEncoder;
    private final Random random = new Random();

    @Autowired
    public DataLoader(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Bean
    public CommandLineRunner initData(UserRepository userRepository,
                                     CommunityRepository communityRepository,
                                     BuildingRepository buildingRepository,
                                     HomeRepository homeRepository,
                                     OwnerRepository ownerRepository,
                                     ParkingRepository parkingRepository,
                                     VehicleRepository vehicleRepository,
                                     RepairRepository repairRepository,
                                     ComplaintRepository complaintRepository,
                                     ActivityRepository activityRepository,
                                     MailboxRepository mailboxRepository,
                                     ParkingUsageRepository parkingUsageRepository,
                                     RoleRepository roleRepository,
                                     PermissionRepository permissionRepository,
                                     RolePermissionRepository rolePermissionRepository,
                                     UserRoleRepository userRoleRepository,
                                     PasswordEncoder passwordEncoder) {

        return args -> {
            logger.info("开始初始化示例数据...");
            
            // 检查是否已有数据
            if (userRepository.count() == 0) {
                // 加载初始角色和权限数据
                loadInitialRolesAndPermissions(roleRepository, permissionRepository, rolePermissionRepository);
                
                // 加载初始用户数据
                loadInitialUsers(userRepository, roleRepository, userRoleRepository, passwordEncoder);
                
                // 其他数据初始化...
                // 创建示例社区
                List<Community> communities = new ArrayList<>();
                if (communityRepository.count() == 0) {
                    String[] communityNames = {"阳光小区", "和平花园", "绿洲居", "幸福家园", "金色年华"};
                    String[] addresses = {"北京市朝阳区", "上海市浦东新区", "广州市天河区", "深圳市南山区", "杭州市西湖区"};
                    String[] developers = {"阳光地产", "和平集团", "绿洲开发", "幸福房产", "金色地产"};

                    for (int i = 0; i < 5; i++) {
                        Community community = new Community();
                        community.setName(communityNames[i]);
                        community.setAddress(addresses[i]);
                        community.setArea(50000.0 + i * 10000);
                        community.setTotalBuildings(10 + i);
                        community.setTotalHomes(500 + i * 100);
                        community.setDeveloperName(developers[i]);
                        community.setPropertyCompany(developers[i] + "物业");
                        community.setCreatedAt(new Date());
                        community.setUpdatedAt(new Date());
                        communities.add(communityRepository.save(community));
                    }
                    logger.info("已创建5个示例社区");
                } else {
                    communities.addAll(communityRepository.findAll());
                }

                // 创建示例楼宇
                List<Building> buildings = new ArrayList<>();
                if (buildingRepository.count() == 0) {
                    for (int i = 0; i < 5; i++) {
                        Building building = new Building();
                        building.setName((i+1) + "号楼");
                        building.setCommunity(communities.get(i % communities.size()));
                        building.setTotalFloors(20 + i);
                        building.setTotalUnits(80 + i * 4);
                        building.setDescription("小区" + (i % 2 == 0 ? "北区" : "南区"));
                        building.setCreatedAt(new Date());
                        building.setUpdatedAt(new Date());
                        buildings.add(buildingRepository.save(building));
                    }
                    logger.info("已创建5个示例楼宇");
                } else {
                    buildings.addAll(buildingRepository.findAll());
                }

                // 创建示例业主
                List<Owner> owners = new ArrayList<>();
                if (ownerRepository.count() == 0) {
                    String[] names = {"张三", "李四", "王五", "赵六", "钱七"};
                    String[] genders = {"男", "女", "男", "女", "男"};
                    String[] phones = {"13800138001", "13800138002", "13800138003", "13800138004", "13800138005"};
                    String[] idCards = {"110101198001010001", "110101198001010002", "110101198001010003", "110101198001010004", "110101198001010005"};

                    for (int i = 0; i < 5; i++) {
                        Owner owner = new Owner();
                        owner.setName(names[i]);
                        owner.setGender(genders[i]);
                        owner.setPhoneNumber(phones[i]);
                        owner.setIdCard(idCards[i]);
                        owner.setProfession("职业" + (i+1));
                        owner.setEmail(names[i] + "@example.com");
                        owner.setCreatedAt(new Date());
                        owner.setUpdatedAt(new Date());
                        owners.add(ownerRepository.save(owner));
                    }
                    logger.info("已创建5个示例业主");
                } else {
                    owners.addAll(ownerRepository.findAll());
                }

                // 创建示例房屋
                List<Home> homes = new ArrayList<>();
                if (homeRepository.count() == 0) {
                    String[] types = {"一室一厅", "两室一厅", "两室两厅", "三室一厅", "三室两厅"};
                    String[] directions = {"朝南", "朝北", "朝东", "朝西", "南北通透"};

                    for (int i = 0; i < 5; i++) {
                        Home home = new Home();
                        home.setBuilding(buildings.get(i % buildings.size()));
                        home.setName((i+1) + "单元" + (101+i));
                        home.setFloor(1 + i);
                        home.setArea(80.0 + i * 10);
                        home.setType(types[i]);
                        home.setDirection(directions[i]);
                        home.setOwner(owners.get(i % owners.size()));
                        home.setStatus(i % 2 == 0 ? "已入住" : "未入住");
                        home.setCreatedAt(new Date());
                        home.setUpdatedAt(new Date());
                        homes.add(homeRepository.save(home));
                    }
                    logger.info("已创建5个示例房屋");
                } else {
                    homes.addAll(homeRepository.findAll());
                }

                // 创建示例停车位
                List<Parking> parkings = new ArrayList<>();
                if (parkingRepository.count() == 0) {
                    for (int i = 0; i < 5; i++) {
                        Parking parking = new Parking();
                        parking.setName("A-" + (101+i));
                        parking.setCommunity(communities.get(i % communities.size()));
                        parking.setType(i % 2 == 0 ? "地下" : "地上");
                        parking.setStatus(i % 2 == 0 ? "已使用" : "空闲");
                        parking.setArea(12.0 + i);
                        parking.setPrice(300.0 + i * 50);
                        parking.setCreatedAt(new Date());
                        parking.setUpdatedAt(new Date());
                        parkings.add(parkingRepository.save(parking));
                    }
                    logger.info("已创建5个示例停车位");
                } else {
                    parkings.addAll(parkingRepository.findAll());
                }

                // 创建示例车辆
                List<Vehicle> vehicles = new ArrayList<>();
                if (vehicleRepository.count() == 0) {
                    String[] brands = {"大众", "丰田", "本田", "现代", "福特"};
                    String[] models = {"帕萨特", "卡罗拉", "雅阁", "索纳塔", "福克斯"};
                    String[] colors = {"黑色", "白色", "红色", "银色", "蓝色"};

                    for (int i = 0; i < 5; i++) {
                        Vehicle vehicle = new Vehicle();
                        vehicle.setLicensePlate("京A" + (12345+i));
                        vehicle.setOwner(owners.get(i % owners.size()));
                        vehicle.setBrand(brands[i]);
                        vehicle.setModel(models[i]);
                        vehicle.setColor(colors[i]);
                        vehicle.setType("小型车");
                        vehicle.setStatus("正常");
                        vehicle.setCreatedAt(new Date());
                        vehicle.setUpdatedAt(new Date());
                        vehicles.add(vehicleRepository.save(vehicle));
                    }
                    logger.info("已创建5个示例车辆");
                } else {
                    vehicles.addAll(vehicleRepository.findAll());
                }

                // 创建示例投诉
                if (complaintRepository.count() == 0) {
                    String[] titles = {"噪音投诉", "环境卫生问题", "设施损坏", "邻里纠纷", "安全隐患"};
                    String[] contents = {
                        "楼上经常在深夜制造噪音，影响休息",
                        "小区垃圾桶长期没有清理，有异味",
                        "电梯按钮损坏，需要维修",
                        "邻居长期占用公共区域，影响通行",
                        "小区内有安全隐患，需要尽快处理"
                    };
                    String[] types = {"噪音投诉", "环境卫生", "设施设备", "邻里纠纷", "安全隐患"};
                    String[] statuses = {"待处理", "处理中", "已完成", "已驳回", "已取消"};

                    for (int i = 0; i < 5; i++) {
                        Complaint complaint = new Complaint();
                        complaint.setOwner(owners.get(i % owners.size()));
                        complaint.setTitle(titles[i]);
                        complaint.setContent(contents[i]);
                        complaint.setType(types[i]);
                        complaint.setStatus(statuses[i]);
                        complaint.setSubmitTime(new Date());

                        if (i >= 1) {
                            complaint.setHandleTime(new Date());
                            complaint.setHandlerName("管理员" + i);
                        }

                        if (i >= 2) {
                            complaint.setFinishTime(new Date());
                            complaint.setResult("已解决，" + contents[i].substring(0, 10) + "...");
                        }

                        complaint.setCreatedAt(new Date());
                        complaint.setUpdatedAt(new Date());
                        complaintRepository.save(complaint);
                    }
                    logger.info("已创建5个示例投诉");
                }

                // 创建示例维修
                if (repairRepository.count() == 0) {
                    String[] descriptions = {
                        "厨房水管漏水，需要更换",
                        "卧室电路故障，灯无法打开",
                        "大门门锁损坏，无法正常锁门",
                        "客厅墙面有裂缝，可能存在安全隐患",
                        "卧室窗户无法关闭，需要维修"
                    };
                    String[] types = {"水电维修", "水电维修", "门窗维修", "墙面维修", "门窗维修"};
                    String[] statuses = {"待处理", "处理中", "已完成", "已驳回", "已取消"};

                    for (int i = 0; i < 5; i++) {
                        Repair repair = new Repair();
                        repair.setOwner(owners.get(i % owners.size()));
                        repair.setHome(homes.get(i % homes.size()));
                        repair.setDescription(descriptions[i]);
                        repair.setType(types[i]);
                        repair.setStatus(statuses[i]);
                        repair.setReportTime(new Date());
                        repair.setCreatedAt(new Date());
                        repair.setUpdatedAt(new Date());
                        repairRepository.save(repair);
                    }
                    logger.info("已创建5个示例维修");
                }

                // 创建示例活动
                if (activityRepository.count() == 0) {
                    String[] titles = {"社区文化节", "健康讲座", "环保宣传活动", "邻里互助日", "社区运动会"};
                    String[] contents = {
                        "丰富多彩的文化节活动，包括歌舞表演、书画展览等",
                        "专业医生讲解健康知识，免费提供健康咨询",
                        "宣传环保理念，倡导绿色生活方式",
                        "促进邻里关系，互帮互助",
                        "增强社区凝聚力，促进居民健康生活"
                    };
                    String[] locations = {"社区文化中心", "社区会议室", "小区广场", "社区活动室", "小区运动场"};
                    String[] statuses = {"筹备中", "报名中", "进行中", "已结束", "已取消"};

                    for (int i = 0; i < 5; i++) {
                        Activity activity = new Activity();
                        activity.setCommunity(communities.get(i % communities.size()));
                        activity.setTitle(titles[i]);
                        activity.setContent(contents[i]);
                        activity.setLocation(locations[i]);
                        activity.setOrganizer("社区管理委员会");
                        activity.setStartTime(new Date());
                        activity.setEndTime(new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000L)); // 一周后
                        activity.setStatus(statuses[i]);
                        activity.setCreatedAt(new Date());
                        activity.setUpdatedAt(new Date());
                        activityRepository.save(activity);
                    }
                    logger.info("已创建5个示例活动");
                }

                // 创建示例信箱
                if (mailboxRepository.count() == 0) {
                    String[] titles = {"建议增加公共设施", "表扬保安工作", "投诉电梯维护", "建议改善小区环境", "感谢物业工作"};
                    String[] contents = {
                        "建议在小区增加儿童游乐设施，方便孩子们玩耍",
                        "表扬小区保安认真负责，维护了小区安全",
                        "反映电梯经常故障，希望加强维护",
                        "建议增加绿化面积，改善小区环境",
                        "感谢物业工作人员的辛勤工作，提供了良好的服务"
                    };
                    String[] types = {"建议", "表扬", "投诉", "建议", "表扬"};
                    String[] statuses = {"未读", "已读", "已回复", "已解决", "已关闭"};

                    for (int i = 0; i < 5; i++) {
                        Mailbox mailbox = new Mailbox();
                        mailbox.setOwner(owners.get(i % owners.size()));
                        mailbox.setTitle(titles[i]);
                        mailbox.setContent(contents[i]);
                        mailbox.setType(types[i]);
                        mailbox.setStatus(statuses[i]);
                        mailbox.setSubmitTime(new Date());

                        if (i >= 1) {
                            // readTime is not defined in the Mailbox entity
                            // mailbox.setReadTime(new Date());
                            mailbox.setHandlerName("管理员" + i);
                        }

                        if (i >= 2) {
                            mailbox.setReplyContent("感谢您的反馈，我们会认真处理");
                            mailbox.setReplyTime(new Date());
                        }

                        mailbox.setCreatedAt(new Date());
                        mailbox.setUpdatedAt(new Date());
                        mailboxRepository.save(mailbox);
                    }
                    logger.info("已创建5个示例信箱");
                }

                // 创建示例车位使用记录
                if (parkingUsageRepository.count() == 0) {
                    for (int i = 0; i < 5; i++) {
                        ParkingUsage parkingUsage = new ParkingUsage();
                        parkingUsage.setParking(parkings.get(i % parkings.size()));
                        parkingUsage.setOwner(owners.get(i % owners.size()));
                        parkingUsage.setVehicle(vehicles.get(i % vehicles.size()));
                        parkingUsage.setStartDate(new Date());
                        if (i % 2 == 0) {
                            parkingUsage.setEndDate(new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000L)); // 一年后
                        }
                        parkingUsage.setFee(500.0 + i * 100);
                        parkingUsage.setPaymentStatus(i % 2 == 0 ? "已支付" : "未支付");
                        parkingUsage.setRemarks("车位使用记录" + (i+1));
                        parkingUsage.setCreatedAt(new Date());
                        parkingUsage.setUpdatedAt(new Date());
                        parkingUsageRepository.save(parkingUsage);
                    }
                    logger.info("已创建5个示例车位使用记录");
                }
            }

            logger.info("示例数据初始化完成");
        };
    }

    @Transactional
    public void loadInitialRolesAndPermissions(RoleRepository roleRepository, PermissionRepository permissionRepository, RolePermissionRepository rolePermissionRepository) {
        logger.info("开始加载初始角色和权限数据...");
        
        // 创建角色
        Role adminRole = createRoleIfNotExists(roleRepository, "ROLE_ADMIN", "超级管理员", "系统超级管理员，拥有所有权限");
        Role managerRole = createRoleIfNotExists(roleRepository, "ROLE_MANAGER", "小区管理员", "小区管理员，负责管理小区相关事务");
        Role ownerRole = createRoleIfNotExists(roleRepository, "ROLE_OWNER", "业主", "业主用户，可以查看和使用业主相关功能");
        Role staffRole = createRoleIfNotExists(roleRepository, "ROLE_STAFF", "普通员工", "普通员工，拥有有限的操作权限");
        
        // 创建系统管理权限
        Permission systemPermission = createPermissionIfNotExists(permissionRepository, "system", "系统管理", "MENU", null, null, 1);
        Permission userPermission = createPermissionIfNotExists(permissionRepository, "system:user", "用户管理", "MENU", "/system/user", systemPermission.getId(), 1);
        createPermissionIfNotExists(permissionRepository, "system:user:list", "用户列表", "BUTTON", null, userPermission.getId(), 1);
        createPermissionIfNotExists(permissionRepository, "system:user:add", "添加用户", "BUTTON", null, userPermission.getId(), 2);
        createPermissionIfNotExists(permissionRepository, "system:user:edit", "编辑用户", "BUTTON", null, userPermission.getId(), 3);
        createPermissionIfNotExists(permissionRepository, "system:user:delete", "删除用户", "BUTTON", null, userPermission.getId(), 4);
        createPermissionIfNotExists(permissionRepository, "system:user:export", "导出用户", "BUTTON", null, userPermission.getId(), 5);
        
        Permission rolePermission = createPermissionIfNotExists(permissionRepository, "system:role", "角色管理", "MENU", "/system/role", systemPermission.getId(), 2);
        createPermissionIfNotExists(permissionRepository, "system:role:list", "角色列表", "BUTTON", null, rolePermission.getId(), 1);
        createPermissionIfNotExists(permissionRepository, "system:role:add", "添加角色", "BUTTON", null, rolePermission.getId(), 2);
        createPermissionIfNotExists(permissionRepository, "system:role:edit", "编辑角色", "BUTTON", null, rolePermission.getId(), 3);
        createPermissionIfNotExists(permissionRepository, "system:role:delete", "删除角色", "BUTTON", null, rolePermission.getId(), 4);
        
        Permission permissionPermission = createPermissionIfNotExists(permissionRepository, "system:permission", "权限管理", "MENU", "/system/permission", systemPermission.getId(), 3);
        createPermissionIfNotExists(permissionRepository, "system:permission:list", "权限列表", "BUTTON", null, permissionPermission.getId(), 1);
        createPermissionIfNotExists(permissionRepository, "system:permission:add", "添加权限", "BUTTON", null, permissionPermission.getId(), 2);
        createPermissionIfNotExists(permissionRepository, "system:permission:edit", "编辑权限", "BUTTON", null, permissionPermission.getId(), 3);
        createPermissionIfNotExists(permissionRepository, "system:permission:delete", "删除权限", "BUTTON", null, permissionPermission.getId(), 4);
        
        // 创建小区管理权限
        Permission propertyPermission = createPermissionIfNotExists(permissionRepository, "property", "物业管理", "MENU", null, null, 2);
        
        Permission communityPermission = createPermissionIfNotExists(permissionRepository, "property:community", "小区管理", "MENU", "/property/community", propertyPermission.getId(), 1);
        createPermissionIfNotExists(permissionRepository, "property:community:list", "小区列表", "BUTTON", null, communityPermission.getId(), 1);
        createPermissionIfNotExists(permissionRepository, "property:community:add", "添加小区", "BUTTON", null, communityPermission.getId(), 2);
        createPermissionIfNotExists(permissionRepository, "property:community:edit", "编辑小区", "BUTTON", null, communityPermission.getId(), 3);
        createPermissionIfNotExists(permissionRepository, "property:community:delete", "删除小区", "BUTTON", null, communityPermission.getId(), 4);
        
        Permission buildingPermission = createPermissionIfNotExists(permissionRepository, "property:building", "房产管理", "MENU", "/property/building", propertyPermission.getId(), 2);
        createPermissionIfNotExists(permissionRepository, "property:building:list", "栋数列表", "BUTTON", null, buildingPermission.getId(), 1);
        createPermissionIfNotExists(permissionRepository, "property:building:add", "添加栋数", "BUTTON", null, buildingPermission.getId(), 2);
        createPermissionIfNotExists(permissionRepository, "property:building:edit", "编辑栋数", "BUTTON", null, buildingPermission.getId(), 3);
        createPermissionIfNotExists(permissionRepository, "property:building:delete", "删除栋数", "BUTTON", null, buildingPermission.getId(), 4);
        
        Permission homePermission = createPermissionIfNotExists(permissionRepository, "property:home", "房产列表", "MENU", "/property/home", propertyPermission.getId(), 3);
        createPermissionIfNotExists(permissionRepository, "property:home:list", "房产列表", "BUTTON", null, homePermission.getId(), 1);
        createPermissionIfNotExists(permissionRepository, "property:home:add", "添加房产", "BUTTON", null, homePermission.getId(), 2);
        createPermissionIfNotExists(permissionRepository, "property:home:edit", "编辑房产", "BUTTON", null, homePermission.getId(), 3);
        createPermissionIfNotExists(permissionRepository, "property:home:delete", "删除房产", "BUTTON", null, homePermission.getId(), 4);
        
        // 分配权限给角色
        // 超级管理员拥有所有权限
        List<Permission> allPermissions = permissionRepository.findAll();
        for (Permission permission : allPermissions) {
            assignPermissionToRole(rolePermissionRepository, adminRole.getId(), permission.getId());
        }
        
        // 小区管理员拥有小区管理权限
        List<Permission> managerPermissions = permissionRepository.findAll().stream()
                .filter(p -> p.getCode().startsWith("property:"))
                .collect(Collectors.toList());
        for (Permission permission : managerPermissions) {
            assignPermissionToRole(rolePermissionRepository, managerRole.getId(), permission.getId());
        }
        
        // 业主拥有查看权限
        List<Permission> ownerPermissions = permissionRepository.findAll().stream()
                .filter(p -> p.getCode().endsWith(":list"))
                .collect(Collectors.toList());
        for (Permission permission : ownerPermissions) {
            assignPermissionToRole(rolePermissionRepository, ownerRole.getId(), permission.getId());
        }
        
        // 普通员工拥有部分权限
        assignPermissionToRole(rolePermissionRepository, staffRole.getId(), userPermission.getId());
        assignPermissionToRole(rolePermissionRepository, staffRole.getId(), communityPermission.getId());
        
        logger.info("初始角色和权限数据加载完成");
    }

    @Transactional
    public void loadInitialUsers(UserRepository userRepository, RoleRepository roleRepository, UserRoleRepository userRoleRepository, PasswordEncoder passwordEncoder) {
        logger.info("开始加载初始用户数据...");
        
        // 创建超级管理员
        createUserIfNotExists(userRepository, roleRepository, userRoleRepository, passwordEncoder,
                             "admin", "admin123", "系统管理员", "admin@example.com", "13800138000", "ROLE_ADMIN");
        
        // 创建小区管理员
        createUserIfNotExists(userRepository, roleRepository, userRoleRepository, passwordEncoder,
                             "manager", "manager123", "王经理", "manager@example.com", "13800138001", "ROLE_MANAGER");
        
        // 创建业主
        createUserIfNotExists(userRepository, roleRepository, userRoleRepository, passwordEncoder,
                             "owner", "owner123", "李业主", "owner@example.com", "13800138002", "ROLE_OWNER");
        
        // 创建普通员工
        createUserIfNotExists(userRepository, roleRepository, userRoleRepository, passwordEncoder,
                             "staff", "staff123", "张员工", "staff@example.com", "13800138003", "ROLE_STAFF");
        
        logger.info("初始用户数据加载完成");
    }
    
    private Role createRoleIfNotExists(RoleRepository roleRepository, String code, String name, String description) {
        Optional<Role> roleOpt = roleRepository.findByCode(code);
        if (roleOpt.isPresent()) {
            return roleOpt.get();
        }
        
        Role role = new Role();
        role.setCode(code);
        role.setName(name);
        role.setDescription(description);
        return roleRepository.save(role);
    }
    
    private Permission createPermissionIfNotExists(PermissionRepository permissionRepository, String code, String name, String type, String path, Long parentId, Integer sort) {
        Optional<Permission> permissionOpt = permissionRepository.findByCode(code);
        if (permissionOpt.isPresent()) {
            return permissionOpt.get();
        }
        
        Permission permission = new Permission();
        permission.setCode(code);
        permission.setName(name);
        permission.setType(type);
        permission.setPath(path);
        permission.setParentId(parentId);
        permission.setSort(sort);
        return permissionRepository.save(permission);
    }
    
    private void assignPermissionToRole(RolePermissionRepository rolePermissionRepository, Long roleId, Long permissionId) {
        // 检查是否已经分配
        List<RolePermission> existingRolePermissions = rolePermissionRepository.findByRoleIdAndPermissionId(roleId, permissionId);
        if (!existingRolePermissions.isEmpty()) {
            return;
        }
        
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(roleId);
        rolePermission.setPermissionId(permissionId);
        rolePermissionRepository.save(rolePermission);
    }

    private User createUserIfNotExists(UserRepository userRepository, RoleRepository roleRepository, UserRoleRepository userRoleRepository, PasswordEncoder passwordEncoder, String username, String password, String fullName, String email, String phoneNumber, String role) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            return userOpt.get();
        }
        
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setFullName(fullName);
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);
        
        User savedUser = userRepository.save(user);
        
        // 分配角色给用户
        Optional<Role> roleOpt = roleRepository.findByCode(role);
        if (roleOpt.isPresent()) {
            UserRole userRole = new UserRole();
            userRole.setUserId(savedUser.getId());
            userRole.setRoleId(roleOpt.get().getId());
            userRoleRepository.save(userRole);
        }
        
        return savedUser;
    }
}
